import React, { useEffect, useState } from "react";
import '../proof.css';
import '../../Login/login.css';
import '../../../App.css'
import { useHistory, useLocation } from "react-router-dom/cjs/react-router-dom";
import { Mask, DotLoading, Toast } from "antd-mobile";
import { useDispatch, useSelector } from "react-redux";
import { PROOF_OCR_USER_STATE_REQ_FAIL, PROOF_OCR_USER_STATE_REQ_SUCCESS, getUserState, isProofBankAccount, isProofFace, isProofFrequentlyUsedApps, isProofMobile, isProofOcr } from "@/store/actions/userState";
import { PageTag } from "@/utils/pageTag";
import ProofNavigateBar from "@/components/ProofNavigateBar";
import { saveEvent } from "@/store/actions/saveEvent";

import icon_idcard_front from '@/assets/icon_idcard_front.png'
import icon_idcard_back from '@/assets/icon_idcard_back.png'

import { isLoanLoaning, isLoanReject, isLoanRepayNow, isLoanReviewing, isLoanSigning } from "@/utils/loanStatus";
import { uploadImage } from "@/store/actions/uploadImage";
import { saveOcr } from "@/store/actions/saveFace";
import Compressor from 'compressorjs';
import AddToHomeGifDialog from "@/components/AddToHomeGifDialog/AddToHomeGifDialog";
import AddHomeEvent from "@/utils/addHomeEvent";
import PrivacyPolicyLink from "@/components/PrivacyPolicyLink/PrivacyPolicyLink";
import OcrTypeFormSelect from "@/components/OcrTypeFormSelect/ocrTypeFormSelect";


/**
 * ocr页
 */
export default function ProofIdCard() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    //选择图片
    const [frontPictureSelected, setFrontPictureSelected] = useState(null)

    //选择图片
    const [backPictureSelected, setBackPictureSelected] = useState(null)

    //图片文件
    const [frontPictureFile, setFrontPictureFile] = useState(null)

    //图片文件
    const [backPictureFile, setBackPictureFile] = useState(null)

    //图片url
    const [frontPicUrl, setFrontPicUrl] = useState(null)

    //图片url
    const [backPicUrl, setBackPicUrl] = useState(null)

    // 获取路由历史 history 对象
    const history = useHistory()

    // 获取路由信息 location 对象
    const location = useLocation()

    //获取 Redux 分发器
    const dispatch = useDispatch()

    //获取Redux Store中的用户状态信息
    const userStateInfo = useSelector(state => state.userState)

    // 选择卡类型
    const [cardType, setCardType] = useState({
        hint: "Téléchargez vos documents d'identification",
        content: "Carte d'identité nationale",
        realContent: "IDCARD",
        title: "Téléchargez vos documents d'identification",
        pickValues: [
            [
                { title: "Carte d'identité nationale", value: "IDCARD", label: "Carte d'identité nationale" },
                { title: "Passeport", value: "PASSPORT", label: "Passeport" },
                { title: "Permis de conduire", value: "DRIVING", label: "Permis de conduire" }
            ]
        ],
    });

    //获取Redux Store中的用户状态信息
    // const userNotExistInfo = useSelector(state => state.userNotExist)

    //查询用户流程状态
    const checkUserStateInfo = async () => {
        console.log("ProofOcr-checkUserStateInfo: ");

        //获取用户状态
        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getUserState(PageTag.PROOF_OCR)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //请求保存接口
    const doUploadImage = async (picFile, isFront = true) => {
        console.log("ProofOcr-doUploadImage: " + isFront);
        console.log(picFile)
        try {
            if (picFile) {
                //显示loading
                setMaskVisible(true)

                //保存打点
                doHitEvent("PROOF_OCR_IMAGE_UPLOAD")

                //获取Action
                const action = uploadImage(picFile, (success, url) => {
                    //显示loading
                    setMaskVisible(false)

                    if (success && url.length > 0) {
                        if (isFront) {
                            setFrontPicUrl(url)
                        } else {
                            setBackPicUrl(url)
                        }
                    } else {
                        if (isFront) {
                            //清空
                            setFrontPictureSelected(null)
                        } else {
                            //清空
                            setBackPictureSelected(null)
                        }
                    }
                })

                //触发接口
                dispatch(action)
            }
        } catch (e) {
            console.log(e)
        }
    }

    //请求保存接口
    const doSaveOcrInfo = async () => {
        console.log("ProofOcr-doSaveOcrInfo: ");
        console.log('frontPicUrl: ' + frontPicUrl)
        console.log('backPicUrl: ' + backPicUrl)

        // { title: "Carte d'identité nationale", value: "IDCARD", label: "Carte d'identité nationale" },
        // { title: "Passeport", value: "PASSPORT", label: "Passeport" },
        // { title: "Permis de conduire", value: "DRIVING", label: "Permis de conduire" }

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = saveOcr(frontPicUrl, backPicUrl, cardType.realContent, (success) => {
                //显示loading
                setMaskVisible(false)

                if (success) {
                    //获取新的用户状态
                    dispatch(getUserState(PageTag.PROOF_OCR))
                }
            })

            //触发接口
            dispatch(action)
        } catch (e) {
            console.log(e)
        }
    }

    //点击提交
    const onHandleSubmit = async () => {
        try {

            console.log('frontPicUrl: ' + frontPicUrl)
            console.log('backPicUrl: ' + backPicUrl)

            if (cardType.realContent !== 'PASSPORT') {
                //上传图片
                if (frontPicUrl && frontPicUrl.length > 0 && backPicUrl && backPicUrl.length > 0) {
                    doSaveOcrInfo()
                } else {
                    //线上版本
                    Toast.show("Veuillez d'abord télécharger la licence")
                }
            } else {
                //上传图片
                if (frontPicUrl && frontPicUrl.length > 0) {
                    doSaveOcrInfo()
                } else {
                    //线上版本
                    Toast.show("Veuillez d'abord télécharger la licence")
                }
            }
        } catch (e) {
            console.log(e)
        }
    }

    //点击返回
    const onHandleNavGoBack = () => {
        console.log("go back")
        history.goBack()
    }

    //拍照返回
    const onHandleFrontImageUpload = (event) => {
        console.log("onHandleFrontImageUpload")
        //更新图片文件
        const file = event.target.files[0];
        console.log(file)

        if (file) {
            console.log("file size " + file.size)
            let quality = 0.4
            if (file.size < 1000 * 1000) { //小于1M
                quality = 0.6
            } else if (file.size < 2000 * 1000) { //小于5M
                quality = 0.4
            } else if (file.size < 10000 * 1000) { //小于10M
                quality = 0.2
            } else { //大于10M
                quality = 0.1
            }

            console.log("quality: " + quality)

            new Compressor(file, {
                quality: quality,
                success(result) {
                    console.log("result file size " + result.size)
                    setFrontPictureFile(result)
                    const reader = new FileReader();
                    reader.onload = (event) => {
                        setFrontPictureSelected(reader.result)
                    };
                    reader.readAsDataURL(result);

                    // 上传图片
                    doUploadImage(result, true)
                }
            })
        } else {
            setFrontPictureSelected(null)
        }
    }

    //拍照返回
    const onHandleBackImageUpload = (event) => {
        console.log("onHandleBackImageUpload")
        //更新图片文件
        const file = event.target.files[0];
        console.log(file)

        if (file) {
            console.log("file size " + file.size)
            let quality = 0.4
            if (file.size < 1000 * 1000) { //小于1M
                quality = 0.6
            } else if (file.size < 2000 * 1000) { //小于5M
                quality = 0.4
            } else if (file.size < 10000 * 1000) { //小于10M
                quality = 0.2
            } else { //大于10M
                quality = 0.1
            }

            console.log("quality: " + quality)

            new Compressor(file, {
                quality: quality,
                success(result) {
                    console.log("result file size " + result.size)
                    setBackPictureFile(result)
                    const reader = new FileReader();
                    reader.onload = (event) => {
                        setBackPictureSelected(reader.result)
                    };
                    reader.readAsDataURL(result);

                    // 上传图片
                    doUploadImage(result, false)
                }
            })
        } else {
            setBackPictureSelected(null)
        }
    }

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);
        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 点击add home监听
    const onHandleAddToHome = (type) => {
        console.log(`点击add home监听: ${type}`)
        if (type === 'home') {
            AddHomeEvent.onHandleAddHomeEventClick()
        } else {
            AddHomeEvent.onHandleAddFavoriteEventClick()
        }
    }

    // 关闭add home
    const onHandleAddToHomeClose = () => {
        console.log(`点击close add home监听`)
        setAddHomeMaskVisible(false)
    }

    //点击选择列表监听
    const onHandleSelectedData = async (data) => {
        console.log("onHandleSelectedDataClick: data: " + data);
        //更新用户状态
        try {
            const newState = { ...cardType }
            newState.content = data.label
            newState.realContent = data.value
            setCardType(newState)

        } catch (e) {
            console.log(e)
        }
    }

    //启动时请求首页额度
    useEffect(() => {

        //获取用户状态
        checkUserStateInfo()

        //打点
        doHitEvent("PROOF_OCR_START")

        return () => {
            //打点
            doHitEvent("PROOF_OCR_END")
        }
    }, [])

    // 查询用户流程状态返回监听
    useEffect(() => {
        try {
            console.log("ProofOcr-查询用户流程状态返回监听")
            console.log(userStateInfo)

            if (userStateInfo.status === PROOF_OCR_USER_STATE_REQ_SUCCESS) {
                //隐藏loading
                setMaskVisible(false)
                console.log("Launch-signOrderId: " + userStateInfo.signOrderId)

                //是否为签约中
                const isHomeSigning = isLoanSigning(userStateInfo.signFlag, userStateInfo.signOrderId)
                //是否为审核中
                const isHomeReviewing = isLoanReviewing(userStateInfo.applyStatus)
                //是否为拒绝
                const isHomeReject = isLoanReject(userStateInfo.applyStatus, userStateInfo.orderStatus)
                //是否为放款中
                const isHomeLoaning = isLoanLoaning(userStateInfo.orderStatus)
                //是否为待还款
                const isHomeRepay = isLoanRepayNow(userStateInfo.orderStatus)
                //是否为待进件
                const isHomeNotLoan = ((!isHomeReviewing) && (!isHomeReject) && (!isHomeLoaning) && (!isHomeRepay))
                console.log("Launch-isHomeReviewing: " + isHomeReviewing)
                console.log("Launch-isHomeReject: " + isHomeReject)
                console.log("Launch-isHomeLoaning: " + isHomeLoaning)
                console.log("Launch-isHomeRepay: " + isHomeRepay)
                console.log("Launch-isHomeNotLoan: " + isHomeNotLoan)
                console.log("Launch-isHomeSigning: " + isHomeSigning)

                //跳转状态页
                if (isHomeSigning) {
                    history.replace('/guide')
                    return

                } else if (isHomeReviewing) {
                    history.replace('/review')
                    return

                } else if (isHomeReject) {
                    history.replace('/reject')
                    return

                } else if (isHomeLoaning) {
                    history.replace('/loaning')
                    return

                } else if (isHomeRepay) {
                    history.replace('/repay')
                    return
                }

                //判断下是否已经做完所有认证
                if (userStateInfo.isProofFinish === true) {
                    //跳转申请页
                    history.replace('/apply')
                    return
                }

                //是否为号码认证
                if (isProofMobile(userStateInfo.stepTitle)) {
                    //跳转申请页
                    history.replace('/proofmobile')
                    return
                }

                //是否为常用app认证
                if (isProofFrequentlyUsedApps(userStateInfo.stepTitle)) {
                    //跳转申请页
                    history.replace('/prooffrequentlyapps')
                    return
                }

                //是否为人脸认证
                if (isProofFace(userStateInfo.stepTitle)) {
                    //跳转申请页
                    history.replace('/proofface')
                    return
                }

                //是否为ocr认证
                if (!isProofOcr(userStateInfo.stepTitle)) {
                    //跳转申请页
                    history.replace('/proof')
                    return
                }

                //是否为钱包认证
                if (isProofBankAccount(userStateInfo.stepTitle)) {
                    //跳转申请页
                    history.replace('/proofwalletlist')
                    return
                }

            } else if (userStateInfo.status === PROOF_OCR_USER_STATE_REQ_FAIL) {
                //隐藏loading
                setMaskVisible(false)
            }

        } catch (e) {
            console.log(e)
        }
    }, [userStateInfo])


    //监听用户是否存在
    // useEffect(() => {
    //     if (userNotExistInfo.notExist === true) {
    //         //history.replace('/login')
    //         history.replace('/loginfb')
    //     }
    // }, [userNotExistInfo])

    return (
        <div className="proofRoot">
            {/* <NavBar onBack={() => { history.goBack() }} style={{ 'width': '100%', 'backgroundColor': 'white' }}>Proof</NavBar> */}
            <ProofNavigateBar theme="white" onBackClick={onHandleNavGoBack} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>{userStateInfo.pageTitle}</ProofNavigateBar>

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            <div className="proofContent proofTopMargin0Px proofMainBackground">

                {/* 新增绑卡 */}
                <div className="proofOcrPic">
                    <div className="proofOcrPicContent">
                        <OcrTypeFormSelect
                            placeholder={cardType.hint}
                            value={cardType.content}
                            title={cardType.title}
                            list={cardType.pickValues}
                            onSelectedDataClick={e => { onHandleSelectedData(e) }}
                            autoComplete="off" />
                    </div>
                </div>

                <div className="proofOcrPic">

                    <div className="proofOcrPicContent">
                        <div className="proofOcrPicHeaderTitle">Téléchargez votre carte d'identité</div>

                        <div className="proofOcrPicRow">
                            {(!frontPictureSelected) && <img className="proofOcrPicImg" alt="" src={icon_idcard_front} />}
                            {(frontPictureSelected) && <img className="proofOcrPicImg" alt="" src={frontPictureSelected} />}
                            <div className="proofOcrPicTitle">Photo de l'avant du permis de conduire</div>

                            <input className="proofOcrImageInput"
                                id="proofFrontImageInput"
                                type="file"
                                accept="image/*"
                                onChange={(e) => { onHandleFrontImageUpload(e) }} />
                        </div>

                        {cardType.realContent !== 'PASSPORT' && <div className="proofOcrPicRow">
                            {(!backPictureSelected) && <img className="proofOcrPicImg" alt="" src={icon_idcard_back} />}
                            {(backPictureSelected) && <img className="proofOcrPicImg" alt="" src={backPictureSelected} />}
                            <div className="proofOcrPicTitle">Photo de l'arrière du permis de conduire</div>

                            <input className="proofOcrImageInput"
                                id="proofBackImageInput"
                                type="file"
                                accept="image/*"
                                onChange={(e) => { onHandleBackImageUpload(e) }} />
                        </div>}
                    </div>
                </div>
            </div>

            {/* 点击确定 */}
            <div className="proofApplyBtn">
                <div className="mainButtonGradient" onClick={onHandleSubmit}>Suivant</div>
            </div>
            {/* </div> */}

            {/* privacy policy */}
            <PrivacyPolicyLink pageTag={userStateInfo.pageTitle} showCheckbox={false} linkText="Politique de confidentialité" />

            {/* add home gif dialog */}
            <AddToHomeGifDialog visible={addHomeMaskVisible} onConfirm={onHandleAddToHome} onClose={onHandleAddToHomeClose} isHomeMode={addHomeMaskIsHomeMode} />


            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="overlayContent">
                    <span style={{ fontSize: 24, color: '#ff3141' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div>
    )
}